package com.spring.configurations

import com.annotation.SocketAction
import com.annotation.SocketHandler
import com.util.ActionUtils
import org.slf4j.LoggerFactory
import org.springframework.aop.support.AopUtils
import org.springframework.beans.factory.config.BeanPostProcessor
import kotlin.reflect.full.findAnnotation
import kotlin.reflect.full.functions
import kotlin.reflect.full.hasAnnotation

/**
 * 自动扫描 已经被SocketHandler注解的类中的所有带SocketAction注解的方法
 */
class ActionRegInit : BeanPostProcessor {

    private val logger = LoggerFactory.getLogger(ActionRegInit::class.java)

    init {
        logger.info("auto reg configuration：ActionRegInit")
    }

    override fun postProcessAfterInitialization(bean: Any, beanName: String): Any {
        val targetClass = AopUtils.getTargetClass(bean)
        if (targetClass.isAnnotationPresent(SocketHandler::class.java)) {
            targetClass.kotlin.functions.filter { it.hasAnnotation<SocketAction>() }.forEach {
                logger.debug("new add socket action： {}", it.name)
                ActionUtils.addAction(it.findAnnotation<SocketAction>()!!, it, bean)
            }
        }
        return bean
    }

}